package com.project.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.server.common.exception.BusinessException;
import com.project.server.dto.LoginDTO;
import com.project.server.dto.LoginVO;
import com.project.server.entity.SysUser;
import com.project.server.mapper.SysUserMapper;
import com.project.server.service.SysUserService;
import com.project.server.utils.JwtUtil;
import com.project.server.vo.doctor.DoctorVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import com.project.server.dto.UserQueryDTO;
import com.project.server.dto.UserDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.time.LocalDateTime;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 查询用户
        SysUser user = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, loginDTO.getUsername()));

        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        if (user.getStatus() != 1) {
            throw new RuntimeException("账号已被禁用");
        }

        // 生成token
        String token = JwtUtil.generateToken(user.getUsername(),user.getId());

        // 构建返回对象
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setUserId(user.getId());
        loginVO.setUsername(user.getUsername());
        loginVO.setRealName(user.getRealName());
        loginVO.setAvatar(user.getAvatar());
        loginVO.setRoleId(user.getRoleId());
        loginVO.setIsAuth(user.getIsAuth());
        // 医生在线状态
        loginVO.setOnline(user.getOnline());
        // 医生描述
        loginVO.setSpecialty(user.getSpecialty());

        return loginVO;
    }


    @Override
    public Page<SysUser> getUserPage(Integer current, Integer size, UserQueryDTO query) {
        Page<SysUser> page = new Page<>(current, size);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.hasText(query.getUsername()), SysUser::getUsername, query.getUsername())
                .like(StringUtils.hasText(query.getRealName()), SysUser::getRealName, query.getRealName())
                .eq(query.getRoleId() != null, SysUser::getRoleId, query.getRoleId())
                .orderByDesc(SysUser::getCreateTime);

        return this.page(page, wrapper);
    }

    @Override
    @Transactional
    public void saveUser(UserDTO userDTO) {
        // 检查用户名是否存在
        if (this.checkUsernameExists(userDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        if (userDTO.getRoleId() == 2) {
            user.setConsultationCount(0);
        }

        this.save(user);
    }

    @Override
    @Transactional
    public void updateUser(UserDTO userDTO) {
        SysUser user = this.getById(userDTO.getId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 如果修改了用户名，检查是否存在
        if (!user.getUsername().equals(userDTO.getUsername())
            && this.checkUsernameExists(userDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        BeanUtils.copyProperties(userDTO, user);
        // 如果密码不为空，则更新密码
        if (StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }
        user.setUpdateTime(LocalDateTime.now());

        this.updateById(user);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        SysUser user = new SysUser();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());

        this.updateById(user);
    }

    // 登录名不能重复
    @Override
    public SysUser getByUsername(String username) {
        SysUser sysUser = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRealName, username));
        return sysUser;
    }

    private boolean checkUsernameExists(String username) {
        return this.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)) > 0;
    }


    @Override
    public IPage<SysUser> page(Integer current, Integer size, String name, Long deptId) {
        Page<DoctorVO> page = new Page<>(current, size);
        return userMapper.getAllDoctor(page, name, deptId);
    }






















}
